﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using RushTracker.Core.Data;
using RushTracker.Core.Util;
using RushTracker.Core.Models.Torrents;
using System.IO;
using RushTracker.Core;
using RushTracker.Core.BEncoding;
using RushTracker.Core.Models;
using System.Text;

namespace RushTracker.Web.UI.Handlers
{
    public class DownloadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string tid = context.Request.RequestContext.RouteData.Values["id"].ToString();
            int torrentId = -1;

            if (!Int32.TryParse(tid, out torrentId))
            {
                context.Response.Write("Not a valid id '" + tid + "'");
                return;
            }

            if (context.User == null || !context.User.Identity.IsAuthenticated)
            {
                context.Response.Write("You have no permission to do this");
                return;
            }

            IDataRepository data = IoC.Resolve<IDataRepository>();
            Torrent t = data.GetObjectById<Torrent>(torrentId);
            User u = data.GetObjectById<User>(Convert.ToInt32(context.User.Identity.Name));

            if (t == null)
            {
                context.Response.Write("Could not find torrent");
                return;
            }

            // do something with torrent
            // update hits and so forth
            t.Downloads += 1;
            t.LastActionDate = DateTime.Now;

            data.UpdateObject(t);
            data.Flush();

            // change announce url etc
            StreamReader reader = new StreamReader(Path.Combine(context.Server.MapPath(Site.Instance.UploadPath), t.Information.FileName), true);
            BEncodedDictionary dict = BEncodedDictionary.DecodeTorrent(reader.BaseStream);
            reader.Close();

            dict["announce"] = new BEncodedString(Site.Instance.AnnounceUrl.Replace("{key}", u.Key));
            if (dict.ContainsKey("announce-list"))
                dict.Remove("announce-list");
            // -----------------------

            context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + t.Name + ".torrent");
            context.Response.ContentType = "application/x-bittorrent";
            context.Response.BinaryWrite(dict.Encode());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}